<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <div class="head-container">
          <el-input v-model="leftColumnVal" class="mb-20px" clearable placeholder="请输入商户名称">
            <template #prefix>
              <Icon icon="ep:search" />
            </template>
          </el-input>
        </div>
        <div class="head-container">
          <el-tree
            ref="treeRef"
            :data="treeList"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :props="defaultProps"
            default-expand-all
            highlight-current
            node-key="id"
            @node-click="handleNodeClick"
          />
        </div>
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <!-- 搜 索工作栏 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="form"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item prop="searchValue">
            <el-input
              v-model="form.searchValue"
              clearable
              placeholder="请输入搜索内容"
              @change="handleQuery"
            >
              <template #prefix>
                <Icon icon="ep:search" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="openForm('create', null, null)">
              <Icon icon="ep:plus" class="mr-5px" /> 新 增
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              plain
              :disabled="queryBuilderShow"
              @click="queryBuilderShow = true"
            >
              复杂搜索
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>

      <ContentWrap v-if="queryBuilderShow">
        <el-row
          ><el-col :span="16">
            <tiny-query-builder
              ref="queryBuilder"
              :config="config"
              :query="query"
              :on-query-change="queryChange" /></el-col
          ><el-col :span="8">
            <el-button type="primary" plain @click="handleQuery"> 搜 索 </el-button>
            <el-button type="primary" plain @click="queryBuilderShowFalse">
              清除搜索条件后隐藏
            </el-button></el-col
          ></el-row
        >
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table
          v-loading="loading"
          :data="list"
          row-key="id"
          default-expand-all
          border
          highlight-current-row
          stripe
          @sort-change="sortChange"
          @filter-change="filterChange"
          show-summary
        >
          <el-table-column type="selection" width="64" />
          <el-table-column sortable="true" label="名 称" align="center" prop="name" />
          <el-table-column label="级 别" align="right" prop="level" />
          <el-table-column label="图 片" align="center" prop="picUrl">
            <template #default="scope">
              <img v-if="scope.row.picUrl" :src="scope.row.picUrl" alt="图 片" class="h-100px" />
            </template>
          </el-table-column>

          <el-table-column label="操 作" align="center">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="openForm('create', null, scope.row.id)"
                v-if="scope.row.level < 3"
              >
                新增子分类
              </el-button>
              <el-button link type="primary" @click="openGoodsUpdateForm(scope.row.id)">
                新增商品
              </el-button>
              <el-button link type="primary" @click="openForm(scope.row.id, null)">
                编 辑
              </el-button>
              <el-button link type="danger" @click="handleDel(scope.row.id)"> 删 除 </el-button>
            </template>
          </el-table-column>
        </el-table>
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 表单弹窗：添加/修改 -->
  <update ref="formRef" @success="getPage" />
  <goodsUpdate ref="formGoodsUpdateRef" @success="getPage" />
</template>
<script setup lang="ts" name="GoodsCategory">
import { QueryBuilder as TinyQueryBuilder } from '@opentiny/vue'
import { handleTree } from '@/utils/tree'
import * as Api from '@/api/userCenter/tradeOrder/goods/category'
import * as MerchantApi from '@/api/userCenter/tradeOrder/merchant/merchant'
import update from './update.vue'
import goodsUpdate from '../goods/update.vue'

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const queryBuilderShow = ref(false)

const queryBuilder = ref()

import { operators, defaultOptions } from '@/utils/queryBuilder'

const config = {
  operators,
  ...defaultOptions,
  combinators: [
    {
      name: 'and',
      label: '且'
    },
    {
      name: 'or',
      label: '或'
    }
  ],
  fields: [
    {
      name: 'name',
      label: '名 称'
    }
  ]
}

import { uuid } from '@/utils'

const query = ref({
  id: uuid(),
  combinator: 'and',
  not: false,
  rules: []
})

const queryChange = async (data) => {
  query.value = data
}

const queryBuilderShowFalse = async () => {
  query.value = {
    id: uuid(),
    combinator: 'and',
    not: false,
    rules: []
  }
  queryBuilderShow.value = false
}

const loading = ref(false) // 列表的加载中
const list = ref<any[]>([]) // 列表的数据
const form = ref({
  query: '',
  name: undefined,
  pageNum: 1,
  pageSize: 20,
  searchValue: '',
  filters: '',
  sortOrder: 'DESC', // 排序,asc／desc
  sortName: 'order_num' // 排序,字段
})
let filterArrLet: any[] = []

const queryFormRef = ref() // 搜 索的表单

/** 查询列表 */
const getPage = async () => {
  loading.value = true
  try {
    const data = await Api.getList(form)
    list.value = handleTree(data, 'id', 'parentId')
  } catch (t) {
    console.log(t)
    loading.value = false
    message.error('查询列表失败')
  } finally {
    loading.value = false
  }
}

/** 搜 索按钮操作 */
const handleQuery = () => {
  form.value.query = ''

  if (queryBuilderShow.value) {
    form.value.query = encodeURIComponent(JSON.stringify(query.value))
  }
  form.value.pageNum = 1
  getPage()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: string, parentId?: string) => {
  if (!id) {
    id = uuid()
  }
  formRef.value.open(type, id, parentId)
}

/** 添加/修改操作 */
const formGoodsUpdateRef = ref()
const openGoodsUpdateForm = (goodsCategoryId?: string) => {
  let id = null
  if (!id) {
    id = uuid()
  }
  formGoodsUpdateRef.value.open('create', id, goodsCategoryId)
}

/** 删除按钮操作 */
const handleDel = async (id: string) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await Api.del(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getPage()
  } catch {}
}

const sortChange = async (data) => {
  form.value.sortOrder = data.order.replace(/ending$/, '')
  form.value.sortName = data.prop

  getPage()
}

const filterChange = async (filters) => {
  filterArrLet.push(filters)
  form.value.filters = encodeURIComponent(JSON.stringify(filterArrLet))

  getPage()
}

import { defaultProps } from '@/utils/tree'

const treeList = ref<Tree[]>([]) // 树形结构
const leftColumnVal = ref<string>('')

/** 基于名字过滤 */
const filterNode = (name: string, data: Tree) => {
  if (!name) return true
  return data.name.includes(name)
}

/** 处理左侧树被点击 */
const handleNodeClick = async (row: { [key: string]: any }) => {}

const getShopList = async () => {
  const data = await MerchantApi.arr(null)
  treeList.value = data
}

/** 初始化 **/
onMounted(() => {
  getPage()
  getShopList()
})
</script>
